﻿/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A
 * copy of the license can be found at http://go.microsoft.com/fwlink/?LinkID=131993. If
 * you cannot locate the Microsoft Public License, please send an email to
 * mixon@microsoft.com. By using this source code in any fashion, you are agreeing to
 * be bound by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

using System.Collections.Generic;
using System.Json;
using System.Linq;

namespace MIXOnline.Descry
{
    public static class ExtensionMethods
    {
        public static string ValueOr(this JsonValue v, string keyName, string defaultValue)
        {
            return (v.ContainsKey(keyName) && v[keyName] != null) ? (string)v[keyName] : defaultValue;
        }

        public static int ValueOr(this JsonValue v, string keyName, int defaultValue)
        {
            return (v.ContainsKey(keyName) && v[keyName] != null) ? (int)(v[keyName]) : defaultValue;
        }

        public static List<JsonValue> ToListOrEmpty(this JsonValue v)
        {
            // returns an empty list from a JsonValue if the JsonValue is a list type but set to null
            if (v == null) return new List<JsonValue>();
            else if (v.JsonType == JsonType.Array) return ((JsonArray)v).ToList();
            else return new List<JsonValue>();
        }

    }
}
